var ajaxUrl={
    url:"http://haveit.ca", //正式服务器
    //url:"http://mdw.59156.cn"
    cnurl:"http://www.maplemellow.com", //正式服务器
};
var apiKey = 'wxff4f639d47c1a958';
var mchId = '1497376172';
var partnerKey = '9b7aee20f5a6f68365dbf0f68611d681';
var notifyUrl = 'http://www.fayuanb.com/home/pay/wxnotify';
 
var Interface={
    index:"/app/index/index",//展示首页
    send_verify:"/app/public/send_verify",//获取验证码
    country:"/app/public/country",//获取国家
    register:"/app/public/register",//用户注册
    login:"/app/public/login",//登录
    member_info:"/app/member/member_info",//获取用户资料
    forget_pass:"/app/public/forget_pass",//忘记密码
    search:"/app/search/index",//搜索
    details:'/app/product/details/',//商品详情
    allsp:'/app/shop/allsp',//商家产品
    change_info:'/app/public/change_info',//修改手机号或者邮箱
    massage_details:'/app/member/massage_details',//消息详情
    info_change:'/app/member/info_change',//修改个人资料
    member_orders:'/app/member/member_orders',//我的订单
    order_detail:'/app/member/order_detail',//订单详情
    address_list:'/app/member/address_list',//收货或者账单地址
    add_address:'/app/member/add_address',// 添加地址或者修改地址
    category_first:'/app/index/category_first',// 所有一级分类
    category_two:'/app/index/category_two',// 二级栏目
    category_three:'/app/index/category_three',// 三级栏目
    merchant_info:'/app/merchant/merchant_info',//获取商户信息
    product_list:'/app/product/index',//根据分类筛选
    member_massage:'/app/member/member_massage',//消息接口
    city:'/app/public/city',//获取城市
    province:'/app/public/province',//获取省份
    join_car:'/app/car/join_car',//加入购物车
    car_del:'/app/car/car_del',//删除购物车
    car_info:'/app/car/car_info',//购物车列表
    change_car_num:'/app/car/change_car_num',//修改购物车
    order_info:'/app/order/order_info',//结算订单
    send_money:'/app/order/send_money',//计算运费
    append_order:'/app/order/append_order',//判断是否有追加订单
    add_order:'/app/pay/add_order',//添加订单
    pay:'/app/pay/go_pay',//支付订单
    scoll_news:'/app/index/scoll_news',//买到快报列表
    product_type:'/app/index/product_type',//产品分类 新到商品 热销商品等
    member_score:'/app/member/member_score',//我的积分列表
    address_id:'/app/member/id_address',//根据地址id获取地址信息
    del_address:'/app/member/del_address',//删除地址
    moren_address:'/app/member/moren_address',//设置默认地址
    member_coupon:'/app/member/member_coupon',//用户优惠券列表
    hot_search:'/app/index/hot_search',//热门搜索
    ziti_addr:'/app/public/ziti_addr',//获取自提
    spell_list:'/app/spell/spell_list',//拼团列表
    member_coupon_list:'/app/member/member_coupon_list',
    member_get_coupon:'/app/member/member_get_coupon',//用户兑换优惠券
    member_collect:'/app/member/member_collect',//收藏夹列表
    join_collect:'/app/car/join_collect',//加入收藏夹
    del_collect:'/app/member/del_collect',//取消收藏
    member_comment:'/app/member/member_comment',//我的评价
    member_orders:'/app/member/member_orders',//我的订单列表
    comm_list:'/app/community/comm_list',//社区list
    commtype:'/app/community/commtype',//社区分类
    merchant_goods:'/app/merchant/merchant_goods',//商品管理
    spell_rule:'/app/spell/spell_rule',//拼团规则
    spell_group:'/app/spell/spell_group',//根据拼团商品查询当前商品的团
    order_detail:'/app/member/order_detail',//根据id获取订单详情
    group_user:'/app/spell/group_user',//根据拼团id获取详情
    product_by_order:'/app/product/product_by_order',//获取评论
    help_center:'/app/public/help_center',//帮助中心
    recived_sure:'/app/member/recived_sure',//确认收货
    go_comment:'/app/member/go_comments',//评价商品
    spike_all_list:'/app/spike/spike_all_list',//秒杀商品
    quxiao_order:'/app/member/quxiao_order',//取消订单
    buy_again:'/app/car/buy_again',//再次购买
    upload:'/app/public/upload',//上传
    list_card:'/app/member/list_card',//银行卡列表
    add_card:'/app/member/add_card',//新增 删除银行卡
    del_card:'/app/member/del_card',//删除银行卡
    merchant_edit:'/app/merchant/merchant_edit',//商家信息修改
    merchant_order:'/app/merchant/merchant_order',//商家订单
    changeShelf:'/app/merchant/changeShelf',//商品上下架
    merchant_goods_info:'/app/merchant/merchant_goods_info',//商家商品详情
    merchant_edit_goods:'/app/merchant/merchant_edit_goods',//修改商家商品
    product_comment:'/app/product/product_comment',//当前商品所有评论
    pay_ok:'/app/pay/pay_ok',//支付成功
    comm_detail:'/app/community/comm_detail',//社区详情
    comm_comment:'/app/community/comm_comment',//发表评论
    comment_list:'/app/community/comment_list',//社区评论列表
    hexiao_status:'/app/merchant/hexiao_status',//核销
    spell_have_stock:'/app/spell/spell_have_stock',//判断拼团商品是否有库存
    comm_zan_zhuan:'/app/community/comm_zan_zhuan',//点赞和转发
    bang:'/app/public/bang',//绑定第三方登录
    shipping_way:'/app/public/shipping_way',//配送方式
    kefu:'/app/public/kefu',//客服
    pay_remind:'/app/public/pay_remind',//支付成展示
    recom_price:'/app/order/recom_price',//使用优惠码
    advertising:'/app/public/advertising',//首页广告
    message_delete:'/app/member/massage_delete',//消息删除
    spike_product:'/app/spike/spike_product',//当前秒杀场次的商品
    pay_total_money:'/app/pay/pay_total_money',//人名币转换成加币
    help_center2:'/app/public/help_center2',//帮助中心
    paypalb_notify:'/app/pay/paypalb_notify',//PayPal支付回调
}
var cnen = $api.getStorage('cnen') || 1;//1是中文，2是英文
var lang= $api.getStorage('lang_type') || {};
var user_type = $api.getStorage('user_type');//用户类型
var islogin=false;//是否登录
var user = $api.getStorage('user')||{};//用户信息
var token = $api.getStorage('token');//token
if($api.getStorage('token') != null && $api.getStorage('token') != "undefined"){
    islogin=true;
}else{
    islogin=false;
}

$(function () {
    window['adaptive'].desinWidth = 750;
    window['adaptive'].baseFont = 28;
    window['adaptive'].maxWidth = 750;
    window['adaptive'].init();
    // console.log(window.screen.availWidth);
     $.fn.autoHeight = function(){
        function autoHeight(elem){
            elem.style.height = 'auto';
            elem.scrollTop = 0; //防抖动
            elem.style.height = elem.scrollHeight + 'px';
        }
        this.each(function(){
            autoHeight(this);
            $(this).on('keyup', function(){
                autoHeight(this);
            });
        });
    }
    $('textarea[autoHeight]').autoHeight();
    getTimeOption();
    $(".close").click(function () {
        $(".modal").fadeOut(300);
    });
    // //筛算按钮
    // $(".wareSelectBox .selectli").click(function(){
    //     //type 1为销量 只有从上到下
    //     //2为上下两边 故清楚dwon和 top
    //     //top从下到上 down 从上到下
    //     var type = $(this).data("type");

    //     console.log(type);
    //     if(type==2){
    //         //如果不为销量，默认从上到下

    //         var ison = $(this).hasClass("on");
    //         console.log(ison);
    //         if(ison){
    //             var istop = $(this).hasClass("top");
    //             if(istop){
    //                 $(this).removeClass("top");
    //                 $(this).addClass("down");
    //             }else{
    //                 $(this).addClass("top");
    //                  $(this).removeClass("down");
    //             }
    //         }else{
    //             $(".wareSelectBox .selectli").removeClass("on");
    //             $(".wareSelectBox .selectli").removeClass("down");
    //             $(".wareSelectBox .selectli").removeClass("top");
    //             $(this).addClass("down");
    //         }
    //         $(this).addClass("on");
    //     }else{
    //         $(".wareSelectBox .selectli").removeClass("on");
    //         $(".wareSelectBox .selectli").removeClass("down");
    //         $(".wareSelectBox .selectli").removeClass("top");
    //         $(this).addClass("on");
    //     }
    // });



    // var ce = $api.getStorage('cn/en');
    // if(isDefine(ce){
    //     cnen = ce;
    // }



});
//调用接口
function getAjax(url, jsonData,fn,fnError) {
    jsonData.lang='ch';
    if(cnen==2){
        jsonData.lang='en';
    }
    jsonData.langType=lang.id;
    // console.log(JSON.stringify(jsonData));
    api.ajax({
        url: ajaxUrl.url + url ,
        method: 'POST',
        data:{body:JSON.stringify(jsonData)},
        headers: {
          "Content-Type": "application/json; charset=utf-8"
        },
    },function(ret, err){
        //console.log(JSON.stringify(ret));
        if (ret) {
            if(ret.code == 200){
                fn(ret);
            }else{
                pop.close();
                //alert(JSON.stringify(ret));
                console.log(ajaxUrl.url + url);
                console.log(JSON.stringify(ret));
                if(ret.code==403){
                    $api.setStorage('token',null);
                    token =null;
                    pop.notice(ret.msg,1.5,function(){
                        historyBack();
                    });
                }else{
                    // alert(ajaxUrl.url + url);
                    // alert(JSON.stringify(err));
                    // alert(JSON.stringify(ret));
                    if(url==Interface.login){//收藏
                        
                    }else{
                        pop.notice(ret.msg);
                    }
                    fnError(ret,err);
                }

            }
        } else {
            pop.close();
            console.log(ajaxUrl.url + url);
            console.log(JSON.stringify(err));
            //（err.code0：连接错误、1：超时、2：授权错误、3：数据类型错误、4：不安全的数据）
            var isnull = false;
            var layers = "";
            switch(err.code){
                case 0:
                layers = "网络不给力哦！请稍后重试";
                isnull = true;
                break;
                case 1:
                layers = "连接超时，请稍后重试";
                isnull = true;
                break;
                case 2:
                layers = "授权错误";
                isnull = true;
                break;
                case 4:
                layers = "不安全的数据";
                isnull = true;
                break;
            }
            if(isnull){
                pop.notice(layers);
            }else{
                if(err.code==3){
                    if(url==Interface.join_collect){//收藏
                        if(cnen==1){
                            pop.notice("已经收藏了！");
                        }else{
                            pop.notice("It's already collection！");
                        }
                    }
                }else{
                    pop.notice(err.msg);
                }
                
                //fnError(err);
            }

        }

    });
}

//上传图片
function upload(files,fn){
    api.ajax({
        url: ajaxUrl.url+Interface.upload,
        method: 'post',
        data: {
            token:token,
            files: {
                'file': files,
            }
        }
    }, function(ret, err) {
        console.log(JSON.stringify(ret));
        console.log(JSON.stringify(err));
        if (ret.code==200) {
            fn(ret);
        } else {
            pop.notice(ret.msg);
        }
    });
   
}


//判断是否为电话或者手机
function regPhoneOrEmail(val){
	var content = "";
	console.log(val);
	console.log();
	console.log((!reg("regTel",val) && !reg("reEmail",val)) || (!reg("reEmail",val) && !reg("regTel",val)));
	if((!reg("regTel",val) && !reg("reEmail",val)) || (!reg("reEmail",val) && !reg("regTel",val))){

    	content="请输入正确的邮箱或手机号";
        if(cnen == 2){
            content ="Please enter the correct telephone or email";
        }
    }
	return content;
}

var zym;
var yzmtime=60;
function yzmsetInterval(){
	yzmtime = Number(yzmtime) - 1;
	var html = "";
	if(yzmtime == 0){
		var html = "获取验证码";
		yzmtime = 60;
		$(".hq_yzm").removeClass("on");
		clearInterval(zym);
	}else{
		var html = yzmtime + "秒后重试";
	}
	$(".hq_yzm").html(html);
}
//删除效果
function deleteElement(e,type){
	var t=1;
	if(isDefine(type)){
            t=type;
        }
	if(t==1){
		e.animate({
	    height:'0',
	    opacity:'0',
	  	margin:'0'
	  },500,function(){
	  	e.hide();
	  });
	}else if(t==2){
		e.animate({
			width:'0',
		    opacity:'0',
		  	margin:'0',
		  },500,function(){
		  	e.hide();
		  });
	}else if(t==3){
        e.animate({
            opacity:'0',
          },500,function(){
            e.hide();
          });
    }

}

function getTimeOption(){
    //得到当前时间
    var date_now = new Date();
    //得到当前年份
    var year = date_now.getFullYear();
    //得到当前月份
    //注：
    //  1：js中获取Date中的month时，会比当前月份少一个月，所以这里需要先加一
    //  2: 判断当前月份是否小于10，如果小于，那么就在月份的前面加一个 '0' ， 如果大于，就显示当前月份
    var month = date_now.getMonth()+1 < 10 ? "0"+(date_now.getMonth()+1) : (date_now.getMonth()+1);
    //得到当前日子（多少号）
    var date = date_now.getDate() < 10 ? "0"+date_now.getDate() : date_now.getDate();
    //设置input标签的max属性
    $(".minDate").attr("min",year+"-"+month+"-"+date);
    $(".maxDate").attr("max",year+"-"+month+"-"+date);
}

//计算弹出框偏移值
function boxCentre(name){
    var add_W = name.width()/2;
    var add_H = name.height()/2;
    console.log(name.height());
    name.css({
        "margin-left": -add_W,
        "margin-top": -add_H,
    });
}
function isDefine(para) {
    if ( typeof para == "undefined" || para == "" || para == "[]" || para == null || para == undefined) {
        return false;
    } else if(typeof para == "number" || para=="number" ||  para == "null"){
        return true;
    }else if(para==null || para==undefined){
        return true;
    }else{
        for (var o in para) {
            return true;
        }
        return false;
    }
}

//弹窗
function maskOpen(){
    $(".mask_pop").addClass("on");
    $(".mask").show();
}

function maskClose(){
    $(".mask_pop").removeClass("on");
    $(".mask").hide();
}
//验证判断
function reg(type,val){
    var regTel=/^[1][3,4,5,7,8][0-9]{9}$/;
    var reEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if(type=="regTel"){
        return regTel.test(val);
    }
    if(type=="reEmail"){
        return reEmail.test(val);
    }

}

function isIdCard(idc){
    var reg =/^(^d{15}$)|(^d{17}([0-9]|X)$)$/;
    return reg.test(reg);

}


//弹出框统一封装
var pop={
    notice:function(content,time,fn){//content 内容 time 时间 单位秒 fn 消息弹出后执行的方法
        //uexWindow.toast('0', '5', content, time*1000);
        var timeVal=2000;
        if(isDefine(time)){
            timeVal=time*1000;
        }
         //提示
         api.toast({
            msg : content,
            duration:timeVal
        });

         if(fn){
            setTimeout(function(){
                fn();
             },timeVal);
        }

    },
    loading:function(text){
        var title="加载中...";
        var txt ="请稍后...";
        if(cnen==2){
            title = 'loading...';
            txt='';
        }
        if(isDefine(text)){
            title=text;
        }
        api.showProgress({
            style : 'default',
            animationType : 'fade',
            title: title,
            text:txt,
            modal: true
        });
    },
    close:function(){
        api.hideProgress();
    }
}

function getImg(url){
    return ajaxUrl.url+url
}

function getWare(item){
    var name = '';
    if(cnen==1){
        name = item.title;
    }else{
        name = item.egname;
    }
    var html= '<li onclick="goWare(\''+item.id+'\')" class="wareItem"><div class="wareImgBox"><img src="'+getImg(item.icon)+'" /></div>'+
        '<div class="wareName"><span>'+name+'</span></div><div class="warePrice">';
        if(item.old_price == ""){
            html+='<span>$'+item.new_price+'</span>';
        }else{
            html+='<span>$'+item.new_price+'</span>';
            html+='<del>'+item.old_price+'</del>';
        }
        html+='</div></li>';
    return html;
}



//下拉刷新
function toDoRequest(){
    api.refreshHeaderLoadDone(); //复位下拉刷新
}

//倒计时
function getCountDown(e,html){
    $(e).each(function(i,item){

        var timer = setInterval(function(){
            var timestamp = $(item).data("time");
            //var nowTime = Date.parse( new Date() ).toString();
            var endTime = timestamp+"000";
            var nowTime = new Date();

            var t = endTime - nowTime.getTime()
            //var t = endTime - nowTime.substr(0,10);
            if(t <= 0){
                clearInterval(timer);
                $(item).html(html+"00:00:00");
                return false;
            }
            // var d=Math.floor(t/1000/60/60/24);
            var hour=Math.floor(t/1000/60/60%24);
            var min=Math.floor(t/1000/60%60);
            var sec=Math.floor(t/1000%60);
            if (hour < 10) {
                 hour = "0" + hour;
            }
            if (min < 10) {
                 min = "0" + min;
            }
            if (sec < 10) {
                 sec = "0" + sec;
            }
            var countDownTime = html+ hour + ":" + min + ":" + sec;
            $(item).html(countDownTime);
        },1000);
    })

}

//退出APP
function ExitApp() {
    var ci = 0;
    var time1, time2;
    api.addEventListener({
        name : 'keyback'
        }, function(ret, err) {
            if (ci == 0) {
                time1 = new Date().getTime();
                ci = 1;
                if(cnen ==1){
                    api.toast({msg:'再按一次返回键退出'});
                }else{
                    api.toast({msg:'Press the return key again to exit'});
                }
                

            } else if (ci == 1) {
            time2 = new Date().getTime();
            if (time2 - time1 < 3000) {
                api.closeWidget({
                    id : api.appId,
                    retData : {
                        name : 'closeWidget'
                    },
                    silent : true
                });
            } else {
                ci = 0;
                if(cnen ==1){
                    api.toast({msg:'再按一次返回键退出'});
                }else{
                    api.toast({msg:'Press the return key again to exit'});
                }
            }
        }
    });
}
//返回首页
function BankIndex() {
    var ci = 0;
    var time1, time2;
    api.addEventListener({
        name : 'keyback'
        }, function(ret, err) {
            if (ci == 0) {
                time1 = new Date().getTime();
                ci = 1;
                if(cnen ==1){
                    api.toast({msg:'再按一次返回键放弃支付'});
                }else{
                    api.toast({msg:'ayment waiver by return once more'});
                }
                

            } else if (ci == 1) {
            time2 = new Date().getTime();
            if (time2 - time1 < 3000) {
                openWin('index','index.html')
            } else {
                ci = 0;
                if(cnen ==1){
                    api.toast({msg:'再按一次返回键放弃支付'});
                }else{
                    api.toast({msg:'ayment waiver by return once more'});
                }
            }
        }
    });
}
//返回首页
var ci = 0;
var time1, time2;
function BankIndexBtn() {
    console.log(ci);
    if (ci == 0) {
        time1 = new Date().getTime();
        ci = 1;
        console.log(ci);
        if(cnen ==1){
            api.toast({msg:'再按一次返回键放弃支付'});
        }else{
            api.toast({msg:'ayment waiver by return once more'});
        }
    } else if (ci == 1) {
        time2 = new Date().getTime();
        if (time2 - time1 < 3000) {
            openWin('index','index.html')
        } else {
            ci = 0;
            if(cnen ==1){
                api.toast({msg:'再按一次返回键放弃支付'});
            }else{
                api.toast({msg:'ayment waiver by return once more'});
            }
        }
    }
}


function timestampToTime(timestamp) {
        //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var date = new Date(timestamp * 1000);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours())+ ':';
        m = (date.getMinutes()< 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
        s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds();
        return Y+M+D+h+m+s;
    }

function timestampToTime2(timestamp) {
        //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var date = new Date(timestamp * 1000);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours())+ ':';
        m = (date.getMinutes()< 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
        s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds();
        return Y+M+D;
}
function hasPermissions(type){
    var resultList = api.hasPermission({
                list:[type]
            });
    console.log(JSON.stringify(resultList));
    return resultList[0].granted;
}

function hasPermissions_camas(){
    var has = hasPermissions('camera');
    var has2 = hasPermissions('storage');
    if(has == false){
        api.requestPermission({
            list: ['camera'],
            code: 100001
        }, function(ret, err){
            console.log(JSON.stringify(ret));
            var result = ret.list[0].granted;
            var never = ret.never;
            if (never == true && result == false){
                api.toast({
                        msg:'请在设置中打开相机的使用权限',
                    });
                return false;
            }
            if(result == false){
                return false;
            }
            if(has2 == false){
                api.requestPermission({
                    list: ['storage'],
                    code: 100001
                }, function(ret, err){
                    console.log(JSON.stringify(ret));
                    var result = ret.list[0].granted;
                    var never = ret.never;
                    if (never == true && result == false){
                        api.toast({
                                msg:'请在设置中打开读取存储空间的权限',
                            });
                        return false;
                    }
                    if(result == false){
                         return false;
                    }
                     return true;
                });
            }
        });
    }else{
        if(has2 == false){
            api.requestPermission({
                list: ['storage'],
                code: 100001
            }, function(ret, err){
                console.log(JSON.stringify(ret));
                var result = ret.list[0].granted;
                var never = ret.never;
                if (never == true && result == false){
                    api.toast({
                            msg:'请在设置中打开读取存储空间的权限',
                        });
                    return false;
                }
                if(result == false){
                     return false;
                }
                return true;
            });
        }
    }
    if(has && has2){
        return true;
    }
}
